package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * @author WeakMoon
     * @date 2025/03/04 20:03:16
     * 监听消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String msg, Message message, Channel channel){
        // 判断消息是否正确发送过来
        if (!StringUtils.isEmpty(msg)) {

            // 解析消息为TrackStatMqVo对象
            TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);

            // 使用businessNo 属性去重，防止消息重复消费
            String businessNo = trackStatMqVo.getBusinessNo();

            // 使用Redis的setIfAbsent功能来确保业务号的唯一处理
            Boolean result = redisTemplate.opsForValue().setIfAbsent("trackStat:" + businessNo, businessNo, 10, TimeUnit.MINUTES);

            // 如果成功设置Redis键值，表示该消息尚未被处理
            if (result) {

                try {
                    // 调用服务层方法更新轨迹统计信息
                    trackInfoService.updateTrackStat(trackStatMqVo);

                } catch (Exception e) {

                    // 如果更新过程中出现异常，删除Redis中的键值，并抛出运行时异常
                    this.redisTemplate.delete("trackStat:" + businessNo);
                    throw new RuntimeException(e);

                }
            }
        }
        // 手动确认消息处理完成
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
